# -*- coding: utf-8 -*-
'''
Created on 2010/07/06

@author: nagai
'''

from kay.utils import forms
from kay.utils.forms.modelform import ModelForm

from kay.i18n import gettext as _
from kay.utils import render_to_response
from kay.auth.decorators import login_required, admin_required
from kay.utils import create_logout_url
from google.appengine.ext import db
from google.appengine.api import images
from datetime import datetime
from kay.utils import set_trace

from werkzeug import (
  unescape, redirect, Response,append_slash_redirect
)

from webfolio.models import Card


class CardAddForm(forms.Form):
    title = forms.TextField(required=True)
    body = forms.TextField(widget=forms.Textarea)
    photo = forms.FileField()
    tags = forms.CommaSeparated(forms.TextField())
    
class CardEditForm(forms.Form):
    key = forms.TextField(required=True, widget=forms.HiddenInput) 
    title = forms.TextField(required=True)
    body = forms.TextField(widget=forms.Textarea)
    photo = forms.FileField(help_text='aaaa')
    tags = forms.CommaSeparated(forms.TextField())
    
    #def __init__(self):
    #    self.photo.help_text = 'aaaaaa'#'
    
@login_required
def card_add(request):
    form = CardAddForm()
    if request.method == "POST":
        if form.validate(request.form, request.files):
            card = Card(title=form['title'],     
                        )
            if request.user.is_authenticated():
                card.author = request.user
            card.title = form['title']
            card.body = form['body']
            if form['photo']:
                photo_org =  images.Image(form['photo'])
                photo_mini =  images.Image(form['photo'])
                #set_trace()
                photo_org.resize(width=700) 
                photo_view = photo_org.execute_transforms(output_encoding=images.JPEG)
                photo_mini.resize(width=100)
                photo_thumb = photo_mini.execute_transforms(output_encoding=images.JPEG)
                card.photo = photo_view
                card.thumbnail = photo_thumb
            card.tags = form['tags']
            card.put()
            return redirect("/")
    return render_to_response("webfolio/add.html", {"form": form.as_widget()})

@login_required
def card_edit(request):
    form = CardEditForm()
    if request.method == "POST":
        if form.validate(request.form, request.files):
            if form['key']:
                card = db.get(form['key'])
                if card.author == request.user:                    
                    card.title = form['title']
                    card.modified = datetime.now()
                    card.body = form['body']
                    if form['photo']:
                        photo_org =  images.Image(form['photo'])
                        photo_mini =  images.Image(form['photo'])
                        #set_trace()
                        photo_org.resize(width=700) 
                        photo_view = photo_org.execute_transforms(output_encoding=images.JPEG)
                        photo_mini.resize(width=100)
                        photo_thumb = photo_mini.execute_transforms(output_encoding=images.JPEG)
                        card.photo = photo_view
                        card.thumbnail = photo_thumb
                    card.tags = form['tags']
                    card.put()
            return redirect("/")
    elif request.method == "GET":
        """"""
        key = request.values['key']
        card = db.get(key)
        if card.author != request.user:
            return redirect("/")
        widget = form.as_widget()
        widget['key']._value=card.key()
        widget['title']._value=card.title
        widget['body']._value=card.body
        #set_trace()
        widget['photo']._field.help_text=u'<img src="/img?key=%s&type=thumb" />Size: %s bytes' % (key, len(card.photo))
        widget['tags']._value=card.tags

    return render_to_response("webfolio/edit.html", {"form": widget})
